package com.xuxx.axontest.demo.workflowdemo;


import com.xuxx.axontest.demo.workflowdemo.config.FlowManagerConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class FlowManagerFactory implements ApplicationContextAware {

    public static FLowManager EMPTY_FLOWMANAGER = new FLowManager() {
        @Override
        public Boolean excute() {
            return true;
        }
    } ;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("给 applicationContext 赋值");
        this.applicationContext = applicationContext;
    }

    //创建 流程管理器
    public FLowManager createFLowManager(FlowManagerConfig config){
        //TODO  此处需要根据 配置 生成工作流管理器

        //获取 所有 工作流组件
        Map<String, FlowComponent> beansOfType = this.applicationContext.getBeansOfType(FlowComponent.class);

        //TODO 创建工作流管理器
        List<String> flowComponentList = config.getFlowComponentList();
        if(CollectionUtils.isEmpty(flowComponentList)){
            return EMPTY_FLOWMANAGER;
        }

        List<FlowComponent> flowComponents = new ArrayList<>(flowComponentList.size());
        for (String s : flowComponentList) {
            FlowComponent flowComponent = beansOfType.get(s);
            if(null != flowComponent) {
                flowComponents.add(flowComponent);
            }
        }

        //返回工作流
        return new FLowManager(){

            private List<FlowComponent> flowComponentsLocal = flowComponents;

            @Override
            public Boolean excute() {

                //TODO 业务代码
                // 1、获取 所有的 可投配置
                // 2、拷贝配置
                // 3、执行 内存过滤

                for (FlowComponent flowComponent : flowComponentsLocal) {
                    if(!flowComponent.excute()){
                        return false;
                    }
                }

                return true;
            }
        };
    }



}
